import { View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import classNames from 'classnames';
import React, { useEffect, useRef, useState } from 'react';
import styles from './index.module.scss';

const Marquee = ({ className, children, step = 30, offset = 0, delay = 1000 }) => {
  // 计算长度的元素ID, 每个组件唯一
  const idRef = useRef('id_' + Math.random().toString(36).slice(-6) + '_' + Date.now());

  // 是否滚动
  const [isMarquee, setIsMarquee] = useState(false);
  // 滚动时长
  const [duration, setDuration] = useState();

  useEffect(() => {
    const query = Taro.createSelectorQuery();
    query.select(`.${styles.Marquee} #${idRef.current}`).fields({ size: true });
    query.select(`.${styles.Marquee}`).fields({ size: true });

    setTimeout(() => {
      query.exec(([child, parent]) => {
        const childWidth = child?.width;
        const parentWidth = parent?.width;

        if (parentWidth && childWidth && parentWidth < childWidth) {
          let seconds = (childWidth / step) * ((childWidth - offset) / childWidth);

          setDuration(`${seconds * 1000}ms`);
          setIsMarquee(true);

          console.log('debug for Marquee status', {
            isMarquee: true,
            step,
            childWidth,
            offset,
            duration: seconds,
          });
        } else {
          setIsMarquee(false);

          console.log('debug for Marquee status', {
            isMarquee: false,
          });
        }
      });
    }, delay);
  }, [children]);

  return (
    <View className={`${styles.Marquee} ${className}`}>
      <View className="outer">
        <View
          id={idRef.current}
          className={classNames('inner', {
            marquee: isMarquee,
          })}
          style={{ animationDuration: duration }}
        >
          {children}
        </View>
      </View>
    </View>
  );
};

export default Marquee;
